//
//  RevanNetworkManager+Extension.swift
//  weibo_swift
//
//  Created by 紫荆秋雪 on 16/12/20.
//  Copyright © 2016年 紫荆秋雪. All rights reserved.
//  封装 微博的网络请求方法

import Foundation



// MARK: - 封装 微博的 网络请求方法
extension RevanNetworkManager {
    
    /// 加载微博数据
    ///
    /// - Parameters:
    ///   - since_id: 返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0
    ///   - max_id: 返回ID小于或等于max_id的微博，默认为0
    ///   - completion: 完成回调[list: 微博字典数组/是否成功]
    func statusList(since_id: Int64 = 0, max_id: Int64 = 0, completion:@escaping (_ list: [[String: AnyObject]]?,_ isSuccess: Bool)->()) {
        //网络请求
        //url
        let URLString = "https://api.weibo.com/2/statuses/public_timeline.json"
        
        // Swift 中 Int 可以转换成 AnyObject ，但是Int64不行，所以要把Int64类型转换成字符串
        let params = ["since_id": since_id, "max_id": (max_id > 0 ? max_id - 1 : 0)]
        
        
        
        //隔离token的请求微博数据方法
        tokenRequest(method: .GET, URLString: URLString, parameters: params) { (json, isSuccess) in
            //获取微博数据
            //把返回来的结果强制转化成“字典”
            let result = json as? [String: AnyObject]
            //在把 result 强制转化成 一个【字典数组】
            let resultJson = result?["statuses"] as? [[String: AnyObject]]
            completion(resultJson, isSuccess)
        }
    }

}

//MAR: - 第二次封装(隔离token)
/*
 func statusList(completion:@escaping (_ list: [[String: AnyObject]]?,_ isSuccess: Bool)->()) {
 //网络请求
 //网络请求
 //url
 let URLString = "https://api.weibo.com/2/statuses/public_timeline.json"
 
 //token
 //        let parameters = ["access_token" : "2.00pBCjdG0D5myUd9451f9e63MHsqHD"];
 tokenRequest(method: .GET, URLString: URLString, parameters: nil) { (json, isSuccess) in
 //获取微博数据
 //把返回来的结果强制转化成“字典”
 let result = json as? [String: AnyObject]
 //在把 result 强制转化成 一个【字典数组】
 let resultJson = result?["statuses"] as? [[String: AnyObject]]
 completion(resultJson, isSuccess)
 }
 }
 */

//MARK: - 第一次封装
/*
    func statusList(completion:@escaping (_ list:Any?,_ isSuccess: Bool)->()) {
        //网络请求
        //url
        let URLString = "https://api.weibo.com/2/statuses/public_timeline.json"
        //token
        let parameters = ["access_token" : "2.00pBCjdG0D5myUd9451f9e63MHsqHD"];
        request(URLString: URLString, parameters: parameters){(json, isSuccess) -> () in
            print("网络回调\(json)")
        }

        request(URLString: URLString, parameters: parameters) { (result, isSuccess) in
            completion(result, isSuccess)
        }
    }
 */


// MARK: - OAuth相关方法（通过授权码code来获取用户accessToken的方法）
extension RevanNetworkManager {
    func loadAccessToken(code: String, complition:@escaping ( _ isSuccess: Bool)->()) {
        // 获取accessToken的网址
        let url = "https://api.weibo.com/oauth2/access_token"
        // 拼接参数
        let params = ["client_id": RevanAppKey,
                      "client_secret": RevanAppSecret,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": RevanRedirectURI]
        // 发起网络请求
        request(method: .POST, URLString: url, parameters: params) { (json, isSuccess) in
            print("json--\(json)")
            // 直接使用 字典 来字典转模型
            self.userAccount.yy_modelSet(with: (json as? [AnyHashable : Any]) ?? [:])
            //保存
//            self.userAccount.saveUserAccount()
            print("json - \(self.userAccount)")
            // 请求用户信息
            self.loadUserInfo(compltion: { (dict) in
                // 直接存储用户信息到 用户模型中
                self.userAccount.yy_modelSet(with: dict)
                print("json - \(self.userAccount)")
                // 保存用户信息到沙盒中
                self.userAccount.saveUserAccount()
                
                // 完成加载AccessToken回调
                complition(isSuccess)
                
            })
            
        }
        
    }
    
}

// MARK: - 获取 未读数 网络请求
extension RevanNetworkManager {
    /// 获取 未读数 网络请求
    func unreadCount(completion: @escaping (Int)->()) {
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        // 参数
        let params = ["uid": RevanUserAccount().uid]
        
        
        tokenRequest(URLString: urlString, parameters: params) { (json, isSuccess) in
            let dict = json as? [String: AnyObject]
            let count = dict?["status"] as? Int
            //回调函数
            completion(count ?? 0)
        }
    }
}

// MARK: - 获取用户信息请求
extension RevanNetworkManager {
    func loadUserInfo(compltion:@escaping (_ dict: [String: AnyObject])->()) {
        // url
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        // uid
        guard let uid = userAccount.uid else {
            return
        }
        let paramet = ["uid": uid]
        
        //发起网络请求
        tokenRequest(URLString: urlString, parameters: paramet) { (json, isSuccess) in
            let dict = json as? [String: AnyObject] ?? [:]
            print(dict)
            compltion(dict)
        }
    }
}


